import utils from "../utils";
import mergeConfig from "./mergeConfig";
import xhr from "./xhr";

// 核心文件

function Axios(config) {
  this.defaults = config;
}

Axios.prototype.request = function (config) {
  // 处理axios(url[,config])
  if (typeof config === "string") {
    config = arguments[1] || {};
    config.url = arguments[0];
  } else {
    config = config || {};
  }

  // 合并config
  config = mergeConfig(this.defaults, config);

  console.log(config);

  // 设置默认method
  if (config.method) {
    config.method = config.method.toLowerCase();
  } else if (this.defaults.method) {
    config.method = this.defaults.method.toLowerCase();
  } else {
    config.method = "get";
  }

  let promise = Promise.resolve(config);
  promise = promise.then(xhr);

  return promise;
};

utils.forEach(["delete", "get", "head", "options"], function (method) {
  Axios.prototype[method] = function (url, config) {
    return this.request(
      utils.merge(config || {}, {
        method: method,
        url: url,
      })
    );
  };
});

utils.forEach(["post", "put", "patch"], function (method) {
  Axios.prototype[method] = function (url, data, config) {
    return this.request(
      utils.merge(config || {}, {
        method: method,
        url: url,
        data: data,
      })
    );
  };
});

export default Axios;
